<template>
  <div class="editUser page">
    <van-nav-bar
        title="编辑用户"
        @click-left="$router.back()"
        left-arrow
    >
      <template #right>
        <span :style="allowEdit ? 'color: #fa59b5' : ''" @click="allowEdit && updateInfo()">保存</span>
      </template>
    </van-nav-bar>
    <div class="user">
      <van-field label="姓名" v-model="form.name" label-width="1.2rem" placeholder="请输入真实姓名"/>
      <van-radio-group v-model="form.sex" checked-color="#fa59b5" direction="horizontal">
        <van-cell-group>
          <van-cell title="性别" title-style="width: 1.2rem">
            <template #right-icon>
              <van-radio name="2">女</van-radio>
              <van-radio style="margin-left: .3rem" name="1">男</van-radio>
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </div>
  </div>
</template>
<script>
import {mapGetters} from "vuex";
import {Toast} from "vant";
import {updateUserInfo} from "@api/User";

export default {
  name: "EditUser",
  computed: {
    allowEdit: function () {
      return this.form && this.form.name && this.form.sex;
    },
    ...mapGetters(["userInfo"])
  },
  created() {
    this.form.name = this.userInfo.name || '';
    this.form.sex = this.userInfo.sex || '1'
  },
  data: function () {
    return {
      form: {
        sex: "1",
        name: ""
      },
      radio: 2
    }
  },
  methods: {
    updateInfo: function () {
      let that = this;
      Toast.loading({
        message: "正在更新用户资料, 请稍等片刻",
        duration: 0,
        forbidClick: false,
        onOpened: function () {
          updateUserInfo({
            name: that.form.name,
            sex: that.form.sex
          }).then(() => {
            Toast.clear();
            Toast.success({
              message: "用户资料更新成功",
              duration: 2000
            })
            that.$store.dispatch("UpdateUserInfo")
            that.userInfo.name = that.form.name;
            that.userInfo.sex = that.form.sex;
          }).catch(() => {
            Toast.clear();
          })
        }
      })
    }
  }
};
</script>
<style scoped>
::v-deep .van-nav-bar__left > i, ::v-deep .van-nav-bar__text, ::v-deep .van-nav-bar__title, ::v-deep .van-cell__title {
  color: var(--van-nav-bar-icon-color);
}

.editUser {
  background-color: #ffffff;
  height: 100%;
  width: 100%;
}

.editUser .user {
  font-size: .37333rem;
  color: #000;
  padding: 0 .37333rem;
}

</style>
